function [THD_N_dB,SNR_dB] = CalculateSNR(data, pn,raw_fs,OSR,freq_list, main_band_limit, str_title)
    % CalculateSNR 计算信噪比 (SNR)
    % data            : 采样数据
    % N               : 采样点数
    % Fs              : 采样率 (Hz)
    % freq_list       : 激励信号频率列表 (Hz)
    % main_band_limit : 主带最大频率 (Hz)
    % str_title       : 类型标题

    snr_data = data(pn*OSR/4+1-OSR+1 : pn*OSR-OSR+1);
    N = length(data)*3/4;
    Fs = raw_fs * OSR;

    % 保证数据长度足够
    if length(snr_data) < N
        error('数据长度小于 N');
    end

    % 截取前 N 个采样
    x = snr_data(1:N);

    % FFT计算
    Y = fft(x);
    P2 = abs(Y / N).^2;  % 双边功率谱
    P1 = P2(1:floor(N/2)+1); % 单边功率谱
    P1(2:end-1) = 2 * P1(2:end-1); % 修正幅值

    % 频率轴
    f = Fs * (0:floor(N/2)) / N;

    % 限制在主带内
    band_mask = f <= main_band_limit;
    f_band = f(band_mask);
    P_band = P1(band_mask);

    % 计算信号能量（freq_list 附近 ±1 FFT bin）
    signal_power = 0;
    bin_width = Fs / N;

    for freq = freq_list
        [~, idx] = min(abs(f_band - freq));
        idx_range = max(1, idx-1) : min(length(P_band), idx+1); % 包含邻近 bin
        signal_power = signal_power + sum(P_band(idx_range));
    end

    % 总功率 & 噪声功率
    total_power = sum(P_band);
    noise_power = total_power - signal_power - P_band(1) -P_band(2);
    noise_power = noise_power / (length(P_band) - length(freq_list));

    % 计算 THD+N
    THD_N_dB = 10* log10(noise_power / signal_power);

    % 计算 SNR
    noise_power_average = (total_power - signal_power) / length(P_band);
    for index=1:length(P_band)
        if((P_band(index) > 4*noise_power_average) &&(index~=idx))
            P_band(index) = noise_power_average;
        end
    end
    total_power = sum(P_band);
    noise_power = total_power - signal_power;
    noise_power = noise_power / (length(P_band) - length(freq_list));
    SNR_dB = 10 * log10(signal_power / noise_power);

    % 打印结果
    fprintf('%s SNR = %.4f dB  THD+N = %.4f dB\n', str_title, SNR_dB,THD_N_dB);
end
